import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {CGoodsRecommendConfigService} from '../../../../../goods/goods-recommend-config-c/goods-recommend-config-c.service';
import {moveItemInArray} from '@angular/cdk/drag-drop';
import {NzMessageService} from 'ng-zorro-antd/message';
import {PageDecorationService} from '../../../page-decoration.service';

@Component({
  selector: 'app-decoration-goods',
  templateUrl: './goods.component.html',
  styleUrls: ['./goods.component.scss']
})
export class GoodsComponent implements OnInit {
  @Input() componentData: any; // 原始数据
  @Output() save = new EventEmitter(); // 保存修改
  @Output() closeComponent = new EventEmitter(); // 关闭
  componentNameDisabled = false; // 组件名输入框禁用状态
  goodsCategoryOptions = [];
  goodsBrandOptions = [];
  query = {
    name: '', // 商品编号或名称
    typeId: '', // 商品类型id
    brandIds: '', // 品牌id
    current: 1,
    size: 10
  };
  goodsModal = {
    visible: false,
    records: [],
    total: 0,
    checkedIds: new Set()
  };
  setOfCheckedId = new Set();
  checked = false;
  indeterminate = false;

  constructor(
    private cGoodsRecommendConfigService: CGoodsRecommendConfigService,
    private nzMessageService: NzMessageService,
    private pageDecorationService:PageDecorationService
  ) {
  }

  ngOnInit(): void {
    this.componentNameDisabled = !!this.componentData?.name;
    this.getGoodsTypeList();
    this.getBrandTypeList();
  }

  addItem() {

  }

  drop(event: any) {
    moveItemInArray(this.componentData.content, event.previousIndex, event.currentIndex);
  }

  removeItem(index: number) {
    this.componentData.content.splice(index, 1);
  }

  getGoodsTypeList() {
    this.cGoodsRecommendConfigService.getGoodsTypeList().subscribe((res: any) => {
      if (res.code === 0) {
        this.goodsCategoryOptions = res.data;
      }
    });
  }

  getBrandTypeList() {
    this.cGoodsRecommendConfigService.getBrandTypeList().subscribe((res: any) => {
      if (res.code === 0) {
        this.goodsBrandOptions = res.data;
      }
    });
  }

  onAllChecked(checked: boolean) {
    this.goodsModal.records.filter((item: any) => !this.goodsModal.checkedIds.has(item.id))
      // @ts-ignore
      .forEach(({id}) => this.updateCheckedSet(id, checked));
    this.refreshCheckedStatus();
  }

  updateCheckedSet(id: number, checked: boolean) {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  refreshCheckedStatus() {
    this.checked = this.goodsModal.records.every(({id}) => this.setOfCheckedId.has(id));
    this.indeterminate = this.goodsModal.records.some(({id}) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }


  onPageIndexChange(index: number) {
    this.query.current = index;
    this.queryGoods();
  }

  onPageSizeChange(pageSize: number) {
    this.query.size = pageSize;
    this.queryGoods();
  }

  queryBtn() {
    this.query.current = 1;
    this.queryGoods();
  }

  resetQuery() {
    this.query = {
      name: '',
      typeId: '',
      brandIds: '',
      current: 1,
      size: 10
    };
    this.queryGoods();
  }

  queryGoods() {
    this.pageDecorationService.getGoods(this.query).subscribe((res: any) => {
      if (res.code === 0) {
        this.goodsModal.total = res.data.total;
        this.goodsModal.records = res.data.records;
      }
    });
  }

  showGoodsModal() {
    this.queryGoods();
    this.goodsModal.visible = true;
    this.goodsModal.checkedIds = new Set(Array.from(this.componentData.content.map((item: any) => item.id)));
  }

  hideGoodsModal() {
    this.goodsModal = {
      visible: false,
      records: [],
      total: 0,
      checkedIds: new Set()
    };
    this.setOfCheckedId = new Set();
    this.checked = false;
    this.indeterminate = false;
  }

  addDevice() {
    this.componentData.content.push(...Array.from(this.setOfCheckedId).map(id => ({id})));
    this.hideGoodsModal();
  }

  saveBtn() {
    if (!this.componentData.content.length) {
      this.nzMessageService.error('至少需要一条数据');
      return;
    }
    this.save.emit(this.componentData);
  }

}
